package com.example.grape_effect.effet.filter

import com.example.grape_effect.gl.common.ShaderConstant


// 双边滤波
class BilateralFilter: LYFilter() {
    init {
        name = "bilateralFilter"
    }
    override var vertexShader = ShaderConstant.NO_FILTER_VERTEX_SHADER
    override var fragmentShader =  """
        precision mediump float;
        varying vec2 textureCoordinate;
        uniform sampler2D inputTexture;
        //uniform float wStep;
        //uniform float hStep;
        const float wStep = 0.001;
        const float hStep = 0.0005;

//        const float wStep = 1.0/750.0;
//        const float hStep = 1.0/770.0;

        float CompareColor(vec4 color1, vec4 color2){

           float l1  =  dot(color1.rgb, vec3(0.3, 0.59, 0.11));
           float l2 =  dot(color2.rgb, vec3(0.3, 0.59, 0.11));

           return smoothstep(0.0, 1.0, 1.0 - abs(l1 - l2));
        }

        void main()
        {

            vec2 delta = vec2(wStep, hStep);
            vec4 col = texture2D(inputTexture, textureCoordinate.xy);
            vec4 col0a = texture2D(inputTexture, textureCoordinate.xy - delta);
            vec4 col0b = texture2D(inputTexture, textureCoordinate.xy + delta);
            vec4 col1a = texture2D(inputTexture, textureCoordinate.xy - 2.0 * delta);
            vec4 col1b = texture2D(inputTexture, textureCoordinate.xy + 2.0 * delta);
            vec4 col2a = texture2D(inputTexture, textureCoordinate.xy - 3.0 * delta);
            vec4 col2b = texture2D(inputTexture, textureCoordinate.xy + 3.0 * delta);

            float w = 0.37004405286;
            float w0a = CompareColor(col, col0a) * 0.31718061674;
            float w0b = CompareColor(col, col0b) * 0.31718061674;
            float w1a = CompareColor(col, col1a) * 0.19823788546;
            float w1b = CompareColor(col, col1b) * 0.19823788546;
            float w2a = CompareColor(col, col2a) * 0.11453744493;
            float w2b = CompareColor(col, col2b) * 0.11453744493;


            vec3 result;
            result = w * col.rgb;
            result += w0a * col0a.rgb;
            result += w0b * col0b.rgb;
            result += w1a * col1a.rgb;
            result += w1b * col1b.rgb;
            result += w2a * col2a.rgb;
            result += w2b * col2b.rgb;
            result /= w + w0a + w0b + w1a + w1b + w2a + w2b;
        //    gl_FragColor = vec4(result.rgb,  1.0);
           vec4 newColor = vec4(result.rgb,  1.0);
            gl_FragColor = mix(newColor, col, 0.5);

        }
    """.trimIndent()


}